package com.carlinfo.stu_ques.common.dao.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.carlinfo.stu_ques.common.dao.IBaseDao;
import com.carlinfo.stu_ques.common.util.FileUtil;

public class BaseDaoimpl<T> implements IBaseDao<T>
{
	
	protected FileUtil fileutil = new FileUtil();
	
	protected File parentFile = new File("data");

	protected int count = 1;
	
	protected int tempId;
	
	public void count()
	{
		count++;
	}
	protected Map<Integer, T> untilMap = new HashMap<Integer, T>();
	
	protected void readFile(File file)
	{
		if(file.exists())
		{
			try
			{
//				System.out.println("====>" + file.getAbsolutePath());
				FileInputStream fileIn = new FileInputStream(file);
				Object obj = fileutil.readFile(fileIn);
				if(obj != null) 
				{
					List<Object> list = (List<Object>) obj;
					this.untilMap = (Map<Integer, T>) list.get(0);
					this.count = (int) list.get(1);
				}
			} catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
		}
	}
	protected void writeFile(File file)
	{
		try
		{
			if(!file.getParentFile().exists())
			{
				file.getParentFile().mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(file);
			List<Object> list = new ArrayList<Object>();
			list.add(untilMap);
			list.add(this.count);
			if(!fileutil.writeFile(fos, list))
			{
				System.out.println("我存失败了");
			}
			
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public int savaOneDao(T t)
	{
		count();
		untilMap.put(tempId, t);
		return tempId;
	}

	@Override
	public void deleteOneDao(T t)
	{
		untilMap.remove(tempId,t);
	}

	@Override
	public void updateOneDao(T t)
	{
		untilMap.put(tempId, t);
	}

	@Override
	public List<T> selectListDao()
	{
		List<T> list = new ArrayList<>();
		if(untilMap != null)
		{
			Set<Entry<Integer, T>> listMap = untilMap.entrySet();
			for (Iterator<Entry<Integer, T>> iterator = listMap.iterator(); iterator.hasNext();)
			{
				Entry<Integer, T> entry =  iterator.next();
				//	entry.getKey();
				//	entry.getValue();
				list.add(entry.getValue());
			}
			return list;
		}
		return null;
	}

	@Override
	public T selectOneDao(Map<String, Object> condMap)
	{
		if(condMap.get("id") != null ) 
		{
			int id = (int) condMap.get("id");
			return untilMap.get(id);
		}
		return null;
	}
	@Override
	public int selectMaxIdDao()
	{
		return this.count;
	}
}
